package org.example.common;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.entity.User;
import org.example.exception.ServiceException;
import org.example.mapper.UserMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtInterceptor implements HandlerInterceptor { //拦截器
    @Resource
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handle){
        String token = request.getHeader("token");  //header里面传过来的参数
        if (StrUtil.isBlank(token)){
            token = request.getParameter("token");  //url参数 ？token=xxx
        }

        // 如果不是映射到方法直接通过,会拿到方法上面的自定义注解
        if (handle instanceof HandlerMethod){
            AuthSccess annotation = ((HandlerMethod) handle).getMethodAnnotation(AuthSccess.class);
            if (annotation != null){
                return true;
            }
        }

        //执行认证
        if (StrUtil.isBlank(token)){
            throw new ServiceException("401","请登录！"); // 权限错误
        }
        // 获取token中的user id
        String userId;
        try{
            userId = JWT.decode(token).getAudience().get(0);    //解码
        }catch (JWTDecodeException j){
            throw new ServiceException("401","请登录！"); // 权限错误
        }

        // 根据token中的userId查询数据库
        User user = userMapper.selectById(Integer.valueOf(userId));
        if (user == null){
            throw new ServiceException("401","请登录！"); // 权限错误
        }

        //通过用户密码加密生成一个验证器
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassWord())).build();
        try{
            jwtVerifier.verify(token); // 验证token
        } catch (JWTVerificationException e){
            throw new ServiceException("401","请登录");
        }
        return true;
    }
}
